package com.vacation.vacationdemo.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vacation.vacationdemo.dto.VacationDto;
import com.vacation.vacationdemo.entity.Dept;
import com.vacation.vacationdemo.entity.Employee;
import com.vacation.vacationdemo.entity.VacationType;
import com.vacation.vacationdemo.service.DeptService;
import com.vacation.vacationdemo.service.VacationService;
import com.vacation.vacationdemo.service.VacationTypeService;
import com.vacation.vacationdemo.util.ThreadLocalUtil;
import com.vacation.vacationdemo.vo.VacationVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 杨光
 * @date 2022年03月09日 11:02
 */
@Controller
@RequestMapping("vacation")
public class VacationController {


    @Autowired
    private VacationService vacationService;
    @Autowired
    private VacationTypeService vacationTypeService;

    @Autowired
    private DeptService deptService;


    @GetMapping("test/exception")
    public String testException(HttpServletRequest request){

        request.setAttribute("errorMsg","测试exception");
        int i=1/0;
        return "forward:/vacation/toindex";
    }


    @Value("${download.filepath}")
    private String downloadFilePath;

    @RequiresPermissions("vacation:toadd")
    @RequestMapping("toadd")
    public String toAddVacation(HttpServletRequest request){


        List<VacationType> vacationTypeList = vacationTypeService.selectVacationType();
        request.setAttribute("vacationTypeList",vacationTypeList);

        return "Vacation";
    }

    @RequiresPermissions("vacation:add")
    @RequestMapping("add")
    public String addVacation(VacationDto vacationDto, HttpServletRequest request){
        HttpSession session = request.getSession();
        Employee loginUser = (Employee)session.getAttribute("loginUser");

        ThreadLocalUtil.EmpThreadLocal.set(loginUser);

        Boolean result = vacationService.addVacation(vacationDto);

        if(result){
            return "forward:/vacation/employee";
        }
        request.setAttribute("errorMsg","添加失败");
        return "Error";
    }
    //使用注解定义接口的访问权限
    @RequiresPermissions("vacation:employee")
    @RequestMapping("employee")
    public String queryVacationForEmployee(
            @RequestParam(value="pageNum",defaultValue = "1") Integer pageNum,
            @RequestParam(value="pageSize",defaultValue = "2") Integer pageSize,
            HttpServletRequest request){

//        HttpSession session = request.getSession();
//        Employee loginUser = (Employee)session.getAttribute("loginUser");
//        ThreadLocalUtil.EmpThreadLocal.set(loginUser);

        PageInfo<VacationVo> pageInfo = vacationService.selectVacation(pageNum, pageSize);

        request.setAttribute("vacationVoList",pageInfo.getList());
        request.setAttribute("pageInfo",pageInfo);

        return "EmployeeVacationList";
    }
    @RequiresPermissions("vacation:cancel:apply")
    @PostMapping("cancel/apply")
    public String calcalApply(Integer vacationId,HttpServletRequest request){
        System.out.println("请求撤销");
        vacationService.cancelApply(vacationId);

        return "forward:/vacation/employee";
    }

    //使用注解定义接口的访问权限
    @RequiresPermissions("vacation:search")
    @RequestMapping("search")
    public String doSearch(
            @RequestParam(value="pageNum",defaultValue = "1") Integer pageNum,
            @RequestParam(value="pageSize",defaultValue = "2") Integer pageSize,
            @RequestParam(value="deptId",defaultValue = "") Integer deptId,
            @RequestParam(value="empName",defaultValue = "") String empName,
            HttpServletRequest request){

//        HttpSession session = request.getSession();
//        Employee loginUser = (Employee)session.getAttribute("loginUser");
//        ThreadLocalUtil.EmpThreadLocal.set(loginUser);

        //查询部门列表
        List<Dept> deptList = deptService.selectAllDepts();

        //查询请假单列表
        PageInfo<VacationVo> pageInfo = vacationService.dynamicSearchVacation(pageNum, pageSize,deptId,empName);

        request.setAttribute("vacationVoList",pageInfo.getList());
        request.setAttribute("pageInfo",pageInfo);
        request.setAttribute("deptList",deptList);

        if(deptId!=null){
            request.setAttribute("selectDeptId",deptId);
        }

        if(empName!=null){
            request.setAttribute("selectEmpName",empName);
        }

        return "ManagerVacationList";
    }

    /**
     * 这个方法把文件写入到nginx的目录中，然后redirect，让浏览器自己再次请求文件下载
     * @author jitwxs
     * @date 2022/3/11 0011 9:31
     * @param deptId
     * @param empName
     * @param request
     * @param response
     * @return java.lang.String
     */
    @RequiresPermissions("vacation:export")
    @RequestMapping("export")
    public String doExport(
            @RequestParam(value="deptId",defaultValue = "") Integer deptId,
            @RequestParam(value="empName",defaultValue = "") String empName,
            HttpServletRequest request,
            HttpServletResponse response){
//
//
//        HttpSession session = request.getSession();
//        Employee loginUser = (Employee)session.getAttribute("loginUser");
//        ThreadLocalUtil.EmpThreadLocal.set(loginUser);

        //查询请假单列表
        String fileName=vacationService.exportVacation(deptId,empName,downloadFilePath);

        //把文件内容写回给客户端
        return "redirect:http://localhost/img/"+fileName;

    }

    /**
     * 这种方式不是通过nginx，直接把文件流通过response写回到浏览器，并设置响应头
     * @author jitwxs
     * @date 2022/3/11 0011 9:32
     * @param deptId
     * @param empName
     * @param request
     * @param response
     * @return java.lang.String
     */
    @RequestMapping("export2")
    public void doExport2(
            @RequestParam(value="deptId",defaultValue = "") Integer deptId,
            @RequestParam(value="empName",defaultValue = "") String empName,
            HttpServletRequest request,
            HttpServletResponse response) {


        HttpSession session = request.getSession();
        Employee loginUser = (Employee) session.getAttribute("loginUser");
        ThreadLocalUtil.EmpThreadLocal.set(loginUser);

        try {
            //生成文件
            String fileName = vacationService.exportVacation(deptId, empName, downloadFilePath);
            File file = new File(downloadFilePath + fileName);

            //把文件内容写回给客户端
            InputStream fis = new BufferedInputStream(new FileInputStream(downloadFilePath + fileName));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");

            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @RequestMapping("batchapprove")
    public String doBatchApprove(HttpServletRequest request){

        HttpSession session = request.getSession();
        Employee loginUser = (Employee) session.getAttribute("loginUser");
        ThreadLocalUtil.EmpThreadLocal.set(loginUser);

        List<Integer> vacationIds = Arrays.stream(request.getParameterValues("vacationIds"))
                .map(vid -> {
            return Integer.valueOf(vid);
        }).collect(Collectors.toList());

        vacationService.doBatchApprove(vacationIds);

        return "forward:/vacation/search";

    }


    //单条记录通过审批
    @RequestMapping("approve")
    public String doApprove(Integer vacationId,HttpServletRequest request){

        HttpSession session = request.getSession();
        Employee loginUser = (Employee) session.getAttribute("loginUser");
        ThreadLocalUtil.EmpThreadLocal.set(loginUser);

        List<Integer> vacationIds = Arrays.asList(vacationId);

        vacationService.doBatchApprove(vacationIds);

        return "forward:/vacation/search";

    }

    //单条记录不通过审批
    @RequestMapping("reject")
    public String doReject(Integer vacationId,HttpServletRequest request){

        HttpSession session = request.getSession();
        Employee loginUser = (Employee) session.getAttribute("loginUser");
        ThreadLocalUtil.EmpThreadLocal.set(loginUser);

        List<Integer> vacationIds = Arrays.asList(vacationId);

        vacationService.doReject(vacationIds);

        return "forward:/vacation/search";

    }


    @RequestMapping("upload")
    public String upload(MultipartFile file){
        vacationService.upload(file);
        return "forward:/vacation/search";
    }

}
